/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package facade;

import entities.NonWorkingDay;
import entities.NonWorkingDayPK;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author PabloSebastian
 */
@Stateless
@Remote (NonWorkingDayFacadeRemote.class)
public class NonWorkingDayFacade extends AbstractFacade<NonWorkingDay> implements NonWorkingDayFacadeRemote {
    @PersistenceContext(unitName = "Javeriana.EJB.EstimatorPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public NonWorkingDayFacade() {
        super(NonWorkingDay.class);
    }
    
    @Override
    public List<Date> findAllByPyme(int pymeIdentification)
    {
        TypedQuery<NonWorkingDay> query = em.createNamedQuery("NonWorkingDay.findByPymeidentification", NonWorkingDay.class).setParameter("pymeidentification", pymeIdentification);
        List<NonWorkingDay> dates  = query.getResultList();
        List<Date> nonWorkingdays = new ArrayList<>();
        for (NonWorkingDay date : dates) 
        {
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.set(Calendar.DAY_OF_MONTH, date.getNonWorkingDayPK().getDay());
            calendar.set(Calendar.MONTH, date.getNonWorkingDayPK().getMonth());
            calendar.set(Calendar.YEAR, date.getNonWorkingDayPK().getYear());
            nonWorkingdays.add(calendar.getTime());         
        }
        
        return nonWorkingdays;
    }

    @Override
    public void saveNonWorkingDays(int pymeIdentification, List<List<Date>> dates) {
       
        for (List<Date> date : dates) {
             NonWorkingDay nonWorkingDay = new NonWorkingDay(date.get(0).getDate(),date.get(0).getMonth(),date.get(0).getYear() + 1900 ,pymeIdentification );
             
             if (this.find(nonWorkingDay.getNonWorkingDayPK()) == null)
             {
                 this.create(nonWorkingDay);
                 
             }
              
        }
    }

    @Override
    public void deleteNonWorkingDays(int pymeIdentification, String date) {
        SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
	try {
		Date castDate = formatter.parse(date);
                int day = castDate.getDate();
                int month = castDate.getMonth();
                int year = castDate.getYear() + 1900;
                this.remove(new NonWorkingDay(day, month, year, pymeIdentification));
	} catch (ParseException e) {     
	} 
    }
}
